using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Sheep_Records;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.Sheep_Records
{
    /// <summary>
    /// 羊只档案创建命令处理器
    /// </summary>
    public class CreateSheepRecordCommandHandler : IRequestHandler<CreateSheepRecordCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<SheepRecords> _sheepRecordRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateSheepRecordCommandHandler> _logger;

        public CreateSheepRecordCommandHandler(
            IBaseRepository<SheepRecords> sheepRecordRepository,
            IMapper mapper,
            ILogger<CreateSheepRecordCommandHandler> logger)
        {
            _sheepRecordRepository = sheepRecordRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理羊只档案创建命令
        /// </summary>
        /// <param name="request">羊只档案创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<ApiResult<int>> Handle(CreateSheepRecordCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("羊只档案创建请求参数为空");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "请求参数不能为空", data = 0 };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"羊只档案创建数据验证失败: {errorMessage}");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = errorMessage, data = 0 };
                }

                // 检查可视化耳号是否已存在
                var existingSheep = await _sheepRecordRepository.GetAll().FirstOrDefaultAsync(s => s.VisibleNumber == request.VisibleNumber && !s.IsDeleted);
                if (existingSheep != null)
                {
                    _logger.LogWarning($"可视化耳号 {request.VisibleNumber} 已存在");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "该可视化耳号已存在", data = 0 };
                }

                // 创建羊只档案实体
                var sheepRecord = new SheepRecords
                {
                    VisibleNumber = request.VisibleNumber,
                    ElectronNumber = request.ElectronNumber,
                    Variety = request.Variety,
                    Gender = request.Gender,
                    DateofBirth = request.DateofBirth,
                    Ageinmonths = request.Ageinmonths,
                    Growthstage = request.Growthstage,
                    Building = request.Building,
                    Column = request.Column,
                    TypeofSheep = request.TypeofSheep,
                    GeneRank = request.GeneRank,
                    ProductionGrade = request.ProductionGrade,
                    SalesLevel = request.SalesLevel,
                    Reproductivestatus = request.Reproductivestatus,
                    PrenatalCheckup = request.PrenatalCheckup,
                    ReproductiveStatusDay = request.ReproductiveStatusDay,
                    BirthWeight = request.BirthWeight,
                    WeaningWeight = request.WeaningWeight,
                    WeaningDate = request.WeaningDate,
                    WeaningAge = request.WeaningAge,
                    FatherNumber = request.FatherNumber,
                    MotherNumber = request.MotherNumber,
                    PresenceStatus = request.PresenceStatus,
                    Note = request.Note,
                    IsDeleted = false
                };
                
                // 执行插入操作
                var result = await _sheepRecordRepository.AddAsync(sheepRecord);
                
                if (result > 0)
                {
                    _logger.LogInformation($"成功创建羊只档案，ID: {result}, 可视化耳号: {request.VisibleNumber}");
                    return new ApiResult<int> { Code = ApiEnum.新增成功, Message = "羊只档案创建成功", data = result };
                }
                else
                {
                    _logger.LogError($"创建羊只档案失败，可视化耳号: {request.VisibleNumber}");
                    return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "羊只档案创建失败", data = 0 };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<int> { Code = ApiEnum.新增失败, Message = ex.Message, data = 0 };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建羊只档案时发生系统异常: {ex.Message}");
                return new ApiResult<int> { Code = ApiEnum.新增失败, Message = "系统异常，请联系管理员", data = 0 };
            }
        }
    }
}